package per.locke.xml.util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.IOException;
import java.util.List;

public class WriteXmlUtil {


    public static Document createXmlRoot(List list, String rootName) throws NoSuchFieldException, IllegalAccessException, IOException {

        Document doc = DocumentHelper.createDocument();

        Element root = doc.addElement(rootName);

        for (Object o : list) {
            String className = ReflectUtil.getClassSimpleName(o);

            Element subEle = root.addElement(className.toLowerCase());

            List<String> fieldNames = ReflectUtil.getFieldNames(o);

            for (String fieldName : fieldNames) {

                Element element = subEle.addElement(fieldName);

                element.setText(ReflectUtil.getFieldValue(o, fieldName));

            }
        }
        return doc;
    }
}
